import glob
import os

import tables

def parse(path):
    with open(path) as fp:
        tokens = fp.read().split()

    npass  = int(tokens[0])
    ntot   = int(tokens[2])

    return npass, ntot

def generate(path):
    path_pass = os.path.join(path, 'pass')

    npass = 0
    for path in glob.iglob(os.path.join(path_pass, '*h5')):
        with tables.openFile(path) as fp:
            npass += len(fp.root.nt)

    path_fail = os.path.join(path, 'fail')

    nfail = 0
    for path in glob.iglob(os.path.join(path_fail, '*h5')):
        with tables.openFile(path) as fp:
            nfail += len(fp.root.nt)
    
    ntot = npath + nfail

    with open('report.txt', 'w') as fp:
        fp.write("{0} / {1} events pass\n".format(npass, ntot))
        
    return npass, ntot

def write(path, npass, ntot, name, pos_str):
    with open(path, 'w') as fp:
        fp.write("{0}/{1} events pass the cut `{2}' ({3})\n".format(npass,
                                                                    ntot,
                                                                    name,
                                                                    pos_str))
